import * as THREE from 'three';

// 灯光配置接口
export interface LightConfig {
  color: number;
  intensity: number;
  distance: number;
  angle?: number;
  penumbra?: number;
  decay?: number;
}

// 车灯系统类
export class CarLightingSystem {
  private scene: THREE.Scene;
  private frontLights: {
    left: THREE.SpotLight;
    right: THREE.SpotLight;
  };
  private rearLights: {
    left: THREE.PointLight;
    right: THREE.PointLight;
  };
  private lightHelpers: THREE.Object3D[] = [];
  private isEnabled: boolean = true;

  constructor(scene: THREE.Scene) {
    this.scene = scene;
    this.createCarLights();
  }

  // 创建车灯
  private createCarLights(): void {
    // 前车灯配置
    const frontLightConfig: LightConfig = {
      color: 0xffffcc,
      intensity: 20.0,
      distance: 15,
      angle: Math.PI / 8,
      penumbra: 0.1,
      decay: 1
    };

    // 后车灯配置
    const rearLightConfig: LightConfig = {
      color: 0xff0000,
      intensity: 0.5,
      distance: 3
    };

    // 创建前车灯 (聚光灯)
    this.frontLights = {
      left: new THREE.SpotLight(
        frontLightConfig.color,
        frontLightConfig.intensity,
        frontLightConfig.distance,
        frontLightConfig.angle,
        frontLightConfig.penumbra,
        frontLightConfig.decay
      ),
      right: new THREE.SpotLight(
        frontLightConfig.color,
        frontLightConfig.intensity,
        frontLightConfig.distance,
        frontLightConfig.angle,
        frontLightConfig.penumbra,
        frontLightConfig.decay
      )
    };

    // 创建后车灯 (点光源)
    this.rearLights = {
      left: new THREE.PointLight(
        rearLightConfig.color,
        rearLightConfig.intensity,
        rearLightConfig.distance
      ),
      right: new THREE.PointLight(
        rearLightConfig.color,
        rearLightConfig.intensity,
        rearLightConfig.distance
      )
    };

    // 启用阴影投射
    Object.values(this.frontLights).forEach(light => {
      light.castShadow = true;
      light.shadow.mapSize.width = 1024;
      light.shadow.mapSize.height = 1024;
      light.shadow.camera.near = 0.1;
      light.shadow.camera.far = 15;
      this.scene.add(light);
      this.scene.add(light.target);
    });

    Object.values(this.rearLights).forEach(light => {
      light.castShadow = true;
      light.shadow.mapSize.width = 512;
      light.shadow.mapSize.height = 512;
      this.scene.add(light);
    });
  }

  // 更新车灯位置和方向
  public updateLights(
    frontLeft: THREE.Vector3,
    frontRight: THREE.Vector3,
    rearLeft: THREE.Vector3,
    rearRight: THREE.Vector3,
    frontDirection: THREE.Vector3,
    isBreaking: boolean = false
  ): void {
    if (!this.isEnabled) return;

    // 更新前车灯位置
    this.frontLights.left.position.copy(frontLeft);
    this.frontLights.right.position.copy(frontRight);

    // 更新前车灯目标位置 (照射方向)
    this.frontLights.left.target.position.copy(
      frontLeft.clone().add(frontDirection.clone().multiplyScalar(10))
    );
    this.frontLights.right.target.position.copy(
      frontRight.clone().add(frontDirection.clone().multiplyScalar(10))
    );

    // 更新后车灯位置
    this.rearLights.left.position.copy(rearLeft);
    this.rearLights.right.position.copy(rearRight);

    // 刹车时增强后车灯亮度
    const rearIntensity = isBreaking ? 1.0 : 0.5;
    this.rearLights.left.intensity = rearIntensity;
    this.rearLights.right.intensity = rearIntensity;
  }

  // 切换车灯开关
  public toggleLights(): void {
    this.isEnabled = !this.isEnabled;
    
    Object.values(this.frontLights).forEach(light => {
      light.visible = this.isEnabled;
    });
    
    Object.values(this.rearLights).forEach(light => {
      light.visible = this.isEnabled;
    });
  }

  // 设置车灯强度
  public setIntensity(frontIntensity: number, rearIntensity: number): void {
    Object.values(this.frontLights).forEach(light => {
      light.intensity = frontIntensity;
    });
    
    Object.values(this.rearLights).forEach(light => {
      light.intensity = rearIntensity;
    });
  }

  // 获取灯光状态
  public isLightEnabled(): boolean {
    return this.isEnabled;
  }

  // 清理资源
  public dispose(): void {
    [...Object.values(this.frontLights), ...Object.values(this.rearLights)].forEach(light => {
      this.scene.remove(light);
      if (light instanceof THREE.SpotLight) {
        this.scene.remove(light.target);
      }
      light.dispose();
    });

    this.lightHelpers.forEach(helper => {
      this.scene.remove(helper);
    });
  }
}

// 环境灯光系统类
export class EnvironmentLightingSystem {
  private scene: THREE.Scene;
  private moonLight: THREE.DirectionalLight;
  private ambientLight: THREE.AmbientLight;
  private villageLights: THREE.PointLight[] = [];

  constructor(scene: THREE.Scene) {
    this.scene = scene;
    this.createEnvironmentLights();
  }

  // 创建环境光照
  private createEnvironmentLights(): void {
    // 月光 (定向光)
    this.moonLight = new THREE.DirectionalLight(0x4444ff, 0.3);
    this.moonLight.position.set(10, 20, 5);
    this.moonLight.target.position.set(0, 0, 0);
    this.moonLight.castShadow = true;
    
    // 配置月光阴影
    this.moonLight.shadow.mapSize.width = 2048;
    this.moonLight.shadow.mapSize.height = 2048;
    this.moonLight.shadow.camera.near = 0.5;
    this.moonLight.shadow.camera.far = 50;
    this.moonLight.shadow.camera.left = -25;
    this.moonLight.shadow.camera.right = 25;
    this.moonLight.shadow.camera.top = 25;
    this.moonLight.shadow.camera.bottom = -25;

    this.scene.add(this.moonLight);
    this.scene.add(this.moonLight.target);

    // 环境光
    this.ambientLight = new THREE.AmbientLight(0x222244, 0.1);
    this.scene.add(this.ambientLight);
  }

  // 添加村庄窗户灯光
  public addVillageLight(position: THREE.Vector3, color: number = 0xffaa44, intensity: number = 0.3): THREE.PointLight {
    const light = new THREE.PointLight(color, intensity, 5);
    light.position.copy(position);
    this.scene.add(light);
    this.villageLights.push(light);
    return light;
  }

  // 创建随机闪烁效果
  public startFlickerEffect(): void {
    const flickerLights = () => {
      this.villageLights.forEach(light => {
        if (Math.random() < 0.02) { // 2% 概率闪烁
          light.intensity = light.intensity > 0 ? 0 : 0.3;
        }
      });
    };

    setInterval(flickerLights, 1000);
  }

  // 调整环境光强度（模拟时间变化）
  public adjustTimeOfDay(timeRatio: number): void {
    // timeRatio: 0 = 深夜, 1 = 黎明
    const moonIntensity = 0.3 * (1 - timeRatio);
    const ambientIntensity = 0.1 + (0.2 * timeRatio);

    this.moonLight.intensity = moonIntensity;
    this.ambientLight.intensity = ambientIntensity;
  }

  // 清理资源
  public dispose(): void {
    this.scene.remove(this.moonLight);
    this.scene.remove(this.moonLight.target);
    this.scene.remove(this.ambientLight);
    
    this.villageLights.forEach(light => {
      this.scene.remove(light);
      light.dispose();
    });
    
    this.moonLight.dispose();
  }
}

// 完整的灯光管理器
export class LightingManager {
  private carLighting: CarLightingSystem;
  private environmentLighting: EnvironmentLightingSystem;

  constructor(scene: THREE.Scene) {
    this.carLighting = new CarLightingSystem(scene);
    this.environmentLighting = new EnvironmentLightingSystem(scene);
  }

  // 获取车灯系统
  public getCarLighting(): CarLightingSystem {
    return this.carLighting;
  }

  // 获取环境灯光系统
  public getEnvironmentLighting(): EnvironmentLightingSystem {
    return this.environmentLighting;
  }

  // 清理所有灯光资源
  public dispose(): void {
    this.carLighting.dispose();
    this.environmentLighting.dispose();
  }
}